package com.ydd.app.action;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.ydd.app.bean.common.CommonResponse;
import com.ydd.app.bean.input.BackstageLoginRequest;
import com.ydd.app.bean.input.CreteUserRequest;
import com.ydd.app.bean.input.CustomerAccountRequest;
import com.ydd.app.bean.input.CustomerLoginRequest;
import com.ydd.app.bean.input.QueryAllCustomersRequest;
import com.ydd.app.bean.output.BackstageLoginResponse;
import com.ydd.app.bean.output.CreteUserResponse;
import com.ydd.app.bean.output.CustomerAccountResponse;
import com.ydd.app.bean.output.CustomerLoginResponse;
import com.ydd.app.bean.output.QueryAllCustomersResponse;
import com.ydd.app.manager.AccountMng;

@Controller
public class AccountAct extends CommonAct{
	private static final Logger  log = Logger.getLogger(AccountAct.class);

	/**
	 * =============
	 * 后台登录
	 * =============
	 */
	@RequestMapping(value = "/backstageLogin.do", method = {RequestMethod.GET,RequestMethod.POST})
	public String backstageLogin(HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		log.info(Thread.currentThread().getStackTrace()[1].getMethodName() + ":" + BEGIN_METHOD);
		// 接口返回配置
		String callback = request.getParameter(CALLBACK);
		BackstageLoginResponse ret = new BackstageLoginResponse();		
		try{
			// 参数获取
			BackstageLoginRequest input = new BackstageLoginRequest();	
			getParameterBean(request, input);

			ret = _accountMng.backstageLogin(input.getUserAccount(),input.getPassword());
			log.info(Thread.currentThread().getStackTrace()[1].getMethodName() + ":" + END_METHOD);
		} catch(Exception e){
			// 接口执行失败
			ret.setCode(STATIC_RET_ERROR_1000);
			ret.setSuccess(false);
			ret.setMessage(msgUtils.getValue("系统异常"));
			
			log.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":" + e.getMessage());
		}
		
		// BEAN转换为JSON数据格式
		CommBeanToJson(ret,response,callback);
		
		return RESULTAPP;
	}
	
	/**
	 * =============
	 * 客户登录
	 * =============
	 */
	@RequestMapping(value = "/customerLogin.do", method = {RequestMethod.GET,RequestMethod.POST})
	public String customerLogin(HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		log.info(Thread.currentThread().getStackTrace()[1].getMethodName() + ":" + BEGIN_METHOD);
		// 接口返回配置
		String callback = request.getParameter(CALLBACK);
		CustomerLoginResponse ret = new CustomerLoginResponse();		
		try{
			// 参数获取
			CustomerLoginRequest input = new CustomerLoginRequest();	
			getParameterBean(request, input);
			ret = _accountMng.customerLogin(input.getUserAccount(),input.getPassword());
			log.info(Thread.currentThread().getStackTrace()[1].getMethodName() + ":" + END_METHOD);
		} catch(Exception e){
			// 接口执行失败
			ret.setCode(STATIC_RET_ERROR_1000);
			ret.setSuccess(false);
			ret.setMessage(msgUtils.getValue("系统异常"));
			
			log.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":" + e.getMessage());
		}
		
		// BEAN转换为JSON数据格式
		CommBeanToJson(ret,response,callback);
		
		return RESULTAPP;
	}
	
	/**
	 * =============
	 * 创建新闻
	 * =============
	 */
	@RequestMapping(value = "/queryAllCustomers.do", method = {RequestMethod.GET,RequestMethod.POST})
	public String queryAllCustomers(HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		log.info(Thread.currentThread().getStackTrace()[1].getMethodName() + ":" + BEGIN_METHOD);
		// 接口返回配置
		String callback = request.getParameter(CALLBACK);
		QueryAllCustomersResponse ret = new QueryAllCustomersResponse();		
		try{
			// 参数获取
			QueryAllCustomersRequest input = new QueryAllCustomersRequest();	
			getParameterBean(request, input);
			ret.setCode(STATIC_RET_OK);
			ret.setCustomers(_accountMng.queryAllCustomers());
			log.info(Thread.currentThread().getStackTrace()[1].getMethodName() + ":" + END_METHOD);
		} catch(Exception e){
			// 接口执行失败
			ret.setCode(STATIC_RET_ERROR_1000);
			ret.setSuccess(false);
			ret.setMessage("系统异常");
			
			log.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":" + e.getMessage());
		}
		
		// BEAN转换为JSON数据格式
		CommBeanToJson(ret,response,callback);
		
		return RESULTAPP;
	}
	
	/**
	 * =============
	 * 创建新闻
	 * =============
	 */
	@RequestMapping(value = "/customerAccount.do", method = {RequestMethod.GET,RequestMethod.POST})
	public String customerAccount(HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		log.info(Thread.currentThread().getStackTrace()[1].getMethodName() + ":" + BEGIN_METHOD);
		// 接口返回配置
		String callback = request.getParameter(CALLBACK);
		CustomerAccountResponse ret = new CustomerAccountResponse();		
		try{
			// 参数获取
			CustomerAccountRequest input = new CustomerAccountRequest();	
			getParameterBean(request, input);
//			ret = _accountMng.customerLogin(input.getUserAccount(),input.getPassword());
			if ( _accountMng.userAccount(input)) {
				ret.setCode(STATIC_RET_OK);
				ret.setSuccess(true);
			}
			else {
				// 接口执行失败
				ret.setCode(STATIC_RET_ERROR_2000);
				ret.setMessage("注册失败");
			}
			log.info(Thread.currentThread().getStackTrace()[1].getMethodName() + ":" + END_METHOD);
		} catch(Exception e){
			// 接口执行失败
			ret.setCode(STATIC_RET_ERROR_1000);
			ret.setSuccess(false);
			ret.setMessage("系统异常");
			
			log.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":" + e.getMessage());
		}
		
		// BEAN转换为JSON数据格式
		CommBeanToJson(ret,response,callback);
		
		return RESULTAPP;
	}
	
	/**
	 * =============
	 * 创建新闻
	 * =============
	 */
	@RequestMapping(value = "/createUser.do", method = {RequestMethod.GET,RequestMethod.POST})
	public String createUser(HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		log.info(Thread.currentThread().getStackTrace()[1].getMethodName() + ":" + BEGIN_METHOD);
		// 接口返回配置
		String callback = request.getParameter(CALLBACK);
		CreteUserResponse ret = new CreteUserResponse();		
		try{
			// 参数获取
			CreteUserRequest input = new CreteUserRequest();	
			getParameterBean(request, input);
			if ( _accountMng.creteUser(input)) {
				ret.setCode(STATIC_RET_OK);
				ret.setSuccess(true);
			}
			else {
				// 接口执行失败
				ret.setCode(STATIC_RET_ERROR_2000);
				ret.setMessage("注册失败");
			}
			log.info(Thread.currentThread().getStackTrace()[1].getMethodName() + ":" + END_METHOD);
		} catch(Exception e){
			// 接口执行失败
			ret.setCode(STATIC_RET_ERROR_1000);
			ret.setSuccess(false);
			ret.setMessage("系统异常");
			
			log.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":" + e.getMessage());
		}
		
		// BEAN转换为JSON数据格式
		CommBeanToJson(ret,response,callback);
		
		return RESULTAPP;
	}
	
	/**
	 * =============
	 * 图片上传
	 * =============
	 */
	@RequestMapping(value = "/upload.do", method = {RequestMethod.GET,RequestMethod.POST})
	public String upload(HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		log.info(Thread.currentThread().getStackTrace()[1].getMethodName() + ":" + BEGIN_METHOD);
		// 接口返回配置
		String callback = request.getParameter(CALLBACK);
		CommonResponse ret = new CommonResponse();		
		try{
			
			
			request.setCharacterEncoding("utf-8");  //设置编码
	        //获得磁盘文件条目工厂
	        DiskFileItemFactory factory = new DiskFileItemFactory();
	        //获取文件需要上传到的路径
	        String path = request.getRealPath("/upload/");
//	      String path = "D:/";
	        //如果没以下两行设置的话，上传大的 文件 会占用 很多内存，
	        //设置暂时存放的 存储室 , 这个存储室，可以和 最终存储文件 的目录不同
	        /**
	         * 原理 它是先存到 暂时存储室，然后在真正写到 对应目录的硬盘上， 
	         * 按理来说 当上传一个文件时，其实是上传了两份，第一个是以 .tem 格式的 
	         * 然后再将其真正写到 对应目录的硬盘上
	         */
	        factory.setRepository(new File(path));
	        //设置 缓存的大小，当上传文件的容量超过该缓存时，直接放到 暂时存储室
	        factory.setSizeThreshold(1024*1024) ;
	        //高水平的API文件上传处理
	        ServletFileUpload upload = new ServletFileUpload(factory);
	        try {
	            //可以上传多个文件
	            List<FileItem> list = (List<FileItem>)upload.parseRequest(request);
	            for(FileItem item : list){
	                //获取表单的属性名字
	                String name = item.getFieldName();
	                //如果获取的 表单信息是普通的 文本 信息
	                if(item.isFormField()){
	                    //获取用户具体输入的字符串 ，名字起得挺好，因为表单提交过来的是 字符串类型的
	                    String value = item.getString() ;
	                    request.setAttribute(name, value);
	                }else{//对传入的非 简单的字符串进行处理 ，比如说二进制的 图片，电影这些
	                    /**
	                     * 以下三步，主要获取 上传文件的名字
	                     */
	                    //获取路径名
	                    String value = item.getName() ;
	                    //索引到最后一个反斜杠
	                    int start = value.lastIndexOf("\\");
	                    //截取 上传文件的 字符串名字，加1是 去掉反斜杠，
	                    String filename = value.substring(start+1);
	                    request.setAttribute(name, filename);
	                    //真正写到磁盘上
	                    //它抛出的异常 用exception 捕捉
	                    //item.write( new File(path,filename) );//第三方提供的
	                    //手动写的
	                    OutputStream out = new FileOutputStream(new File(path,filename));
	                    InputStream in = item.getInputStream() ;
	                    int length = 0 ;
	                    byte [] buf = new byte[1024] ;
	                    // in.read(buf) 每次读到的数据存放在   buf 数组中
	                    while( (length = in.read(buf) ) != -1){
	                        //在   buf 数组中 取出数据 写到 （输出流）磁盘上
	                        out.write(buf, 0, length);
	                    }
	                    in.close();
	                    out.close();
	                }
	            }
	            ret.setCode(STATIC_RET_OK);
				ret.setSuccess(true);
				
	        }catch (FileUploadException e) {
	        	ret.setCode(STATIC_RET_ERROR_1000);
				ret.setSuccess(false);
				ret.setMessage("系统异常");
				
				log.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":" + e.getMessage());
	        }catch (Exception e) {
	        	ret.setCode(STATIC_RET_ERROR_1000);
				ret.setSuccess(false);
				ret.setMessage("系统异常");
				
				log.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":" + e.getMessage());
	        }
			log.info(Thread.currentThread().getStackTrace()[1].getMethodName() + ":" + END_METHOD);
		} catch(Exception e){
			// 接口执行失败
			ret.setCode(STATIC_RET_ERROR_1000);
			ret.setSuccess(false);
			ret.setMessage("系统异常");
			
			log.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":" + e.getMessage());
		}
		
		// BEAN转换为JSON数据格式
		CommBeanToJson(ret,response,callback);
		
		return RESULTAPP;
	}
	
	@Autowired
	private AccountMng _accountMng;

}
